package com.piece.core.authentication.service;

import com.piece.core.framework.constant.SecurityConstants;
import com.piece.core.framework.util.cache.CacheFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.oauth2.common.exceptions.InvalidClientException;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.NoSuchClientException;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.util.CollectionUtils;
import javax.sql.DataSource;
import java.util.List;

/**
 * oauth_client_details表数据缓存
 */
@Slf4j
public class CustomClientDetailsService extends JdbcClientDetailsService {

    private CacheFactory cacheFactory;

    public CustomClientDetailsService(DataSource dataSource, CacheFactory cacheFactory) {
        super(dataSource);
        this.cacheFactory = cacheFactory;
    }

    @Override
    public ClientDetails loadClientByClientId(String clientId) {
        ClientDetails clientDetails = cacheFactory.get().getHash(SecurityConstants.CACHE_CLIENT_KEY, clientId, BaseClientDetails.class);
        if (null == clientDetails) {
            clientDetails = cacheAndGetClient(clientId);
        }
        return clientDetails;
    }

    /**
     * 缓存client并返回client
     */
    public ClientDetails cacheAndGetClient(String clientId) {
        ClientDetails clientDetails = null;
        try {
            clientDetails = super.loadClientByClientId(clientId);
            if (null != clientDetails) {
                cacheFactory.get().setHash(SecurityConstants.CACHE_CLIENT_KEY, clientId, clientDetails);
            }
        } catch (NoSuchClientException e) {
            log.error("未找到clientId[{}]", clientId);
        } catch (InvalidClientException e) {
            log.error("clientId[{}]已无效", clientId, e);
        }
        return clientDetails;
    }

    @Override
    public void addClientDetails(ClientDetails clientDetails) {
        // super.addClientDetails(clientDetails);
        cacheAndGetClient(clientDetails.getClientId());
    }

    @Override
    public void updateClientDetails(ClientDetails clientDetails) {
        // super.updateClientDetails(clientDetails);
        cacheAndGetClient(clientDetails.getClientId());
    }

    @Override
    public void updateClientSecret(String clientId, String secret) {
        // super.updateClientSecret(clientId, secret);
        cacheAndGetClient(clientId);
    }

    @Override
    public void removeClientDetails(String clientId) {
        // super.removeClientDetails(clientId);
        removeClientCache(clientId);
    }

    /**
     * 删除redis缓存
     */
    private void removeClientCache(String clientId) {
        cacheFactory.get().delete(SecurityConstants.CACHE_CLIENT_KEY, clientId);
    }

    /**
     * 将oauth_client_details全表刷入redis
     */
    public void loadAllClientToCache() {
        cacheFactory.get().delete(SecurityConstants.CACHE_CLIENT_KEY);

        List<ClientDetails> list = super.listClientDetails();
        if (CollectionUtils.isEmpty(list)) {
            log.error("oauth_client_details表数据为空，请检查");
            return;
        }

        list.parallelStream().forEach(client -> cacheFactory.get().setHash(SecurityConstants.CACHE_CLIENT_KEY, client.getClientId(), client));
    }
}
